package org.jarraiders.musiclibrary.client.presenter;

import org.jarraiders.musiclibrary.client.AlbumsServiceAsync;
import org.jarraiders.musiclibrary.client.event.AlbumUpdatedEvent;
import org.jarraiders.musiclibrary.client.event.EditAlbumCancelledEvent;
import org.jarraiders.musiclibrary.shared.domain.AlbumDTO;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class EditAlbumPresenter implements Presenter {
	public interface Display {
		HasClickHandlers getSaveButton();

		HasClickHandlers getCancelButton();

		HasValue<String> getAlbumName();

		HasValue<String> getAlbumYear();

		Widget asWidget();
	}

	private AlbumDTO album;
	private final AlbumsServiceAsync rpcService;
	private final HandlerManager eventBus;
	private final Display display;

	public EditAlbumPresenter(AlbumsServiceAsync rpcService, HandlerManager eventBus, Display display) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.album = new AlbumDTO();
		this.display = display;
		bind();
	}

	public EditAlbumPresenter(AlbumsServiceAsync rpcService, HandlerManager eventBus, Display display, String id) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = display;
		bind();

		rpcService.getAlbum(id, new AsyncCallback<AlbumDTO>() {
			public void onSuccess(AlbumDTO result) {
				album = result;
				EditAlbumPresenter.this.display.getAlbumName().setValue(album.getAlbumName());
				EditAlbumPresenter.this.display.getAlbumYear().setValue(album.getAlbumYear()+"");

			}

			public void onFailure(Throwable caught) {
				Window.alert("Error retrieving contact");
			}
		});

	}

	public void bind() {
		this.display.getSaveButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				doSave();
			}
		});

		this.display.getCancelButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new EditAlbumCancelledEvent());
			}
		});
	}

	@Override
	public void go(final HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
	}

	private void doSave() {
		album.setAlbumName(display.getAlbumName().getValue());
		album.setAlbumYear(new Integer(display.getAlbumYear().getValue()));
		rpcService.updateAlbum(album, new AsyncCallback<AlbumDTO>() {
			public void onSuccess(AlbumDTO result) {
				eventBus.fireEvent(new AlbumUpdatedEvent(result));
			}

			public void onFailure(Throwable caught) {
				Window.alert("Error updating contact");
			}
		});
	}

}
